<template>
  <div class="ai-chat">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="back" @click="goBack">＜</div>
      <div class="title">快速问诊</div>
      <div class="notification-icon">🔔</div>
      <div class="notification">

      </div>
    </div>

    <!-- 聊天内容区域 -->
    <div class="chat-container" ref="chatContainer">
      <!-- AI欢迎消息 -->
      <div class="message ai-message">
        <div class="avatar">
          <img src="@/assets/images/ai-avatar.png" alt="AI">
        </div>
        <div class="message-content">
          你好，请详细描述您的病情，我们将会安排适合的医生为你服务
        </div>
      </div>

      <!-- 聊天记录 -->
      <div
        v-for="(msg, index) in chatMessages"
        :key="index"
        :class="['message', msg.type === 'user' ? 'user-message' : 'ai-message']"
      >
        <!-- AI头像和消息 -->
        <template v-if="msg.type === 'ai'">
          <div class="avatar">
            <img src="@/assets/images/ai-avatar.png" alt="AI">
          </div>
          <div class="message-content">
            {{ msg.content }}

            <!-- 医生列表 - 当AI消息中包含推荐时显示 -->
            <div v-if="msg.content.includes('提供的症状') && msg.doctorList && msg.doctorList.length > 0" class="doctor-list">
              <div class="doctor-list-title">为您推荐以下医生：</div>
              <div class="doctor-cards">
                <div v-for="doctor in msg.doctorList" :key="doctor.id" class="doctor-card">
                  <div class="doctor-info">
                    <div class="doctor-name">{{ doctor.doctorName }}</div>
                    <div class="doctor-title">{{ doctor.doctorTitle }}</div>
                    <div class="doctor-specialty">{{ doctor.symptomName }}</div>
                    <div class="doctor-price">￥{{ doctor.doctorPrice }}</div>
                  </div>
                  <div class="doctor-action">
                    <button class="consult-btn" @click="startConsult(doctor)">立即挂号</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>

        <!-- 用户头像和消息 -->
        <template v-else>
          <div class="message-content">{{ msg.content }}</div>
          <div class="avatar">
            <img src="@/assets/images/user-avatar.png" alt="User">
          </div>
        </template>
      </div>
    </div>

    <!-- 底部输入区域 -->
    <div class="input-area">
      <!-- 快速选择按钮 -->
      <div class="quick-replies">
        <div class="quick-reply-hint">您也可以点击标签快速回答：</div>
        <!-- 快速回答标签组 - 这部分是从后端返回的数据 -->
        <div class="tags">
          <div
            v-for="tag in quickReplyTags"
            :key="tag.id"
            class="tag-item"
            @click="selectQuickReply(tag.symptomName)"
          >
            {{ tag.symptomName }}
          </div>
        </div>
      </div>

      <div class="input-box">
        <input
          v-model="inputMessage"
          type="text"
          :placeholder="isLoading ? '请等待...' : '请描述您的症状...'"
          @keyup.enter="sendMessage"
          :disabled="isLoading"
        >
        <div class="send-btn"
             @click="sendMessage"
             :class="{ 'disabled': isLoading }">
          {{ isLoading ? '请等待' : '发送' }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { aiChatStream } from '@/api/ai/ai'
import { lookAtTheCorrespondingDiseaseByLocation } from "@/api/organSelect/organSelect"
import { weCanTraceTheSymptomsToTheDoctor } from "@/api/doctor/doctor"


export default {
  name: 'AiChat',

  data() {
    return {
      inputMessage: '',
      hasNewMessage: false,
      chatMessages: [],
      quickReplyTags: [],
      eventSource: null,
      doctorList: [],
      organId: null,
      isLoading: false
    }
  },
  created() {
    // 加载保存的聊天记录和医生列表
    const savedMessages = localStorage.getItem('chatMessages');
    if (savedMessages) {
      this.chatMessages = JSON.parse(savedMessages);
      // 恢复医生列表
      const lastAiMessage = this.chatMessages.find(msg => 
        msg.type === 'ai' && msg.content.includes('提供的症状') && msg.doctorList
      );
      if (lastAiMessage && lastAiMessage.doctorList) {
        this.doctorList = lastAiMessage.doctorList;
      }
    }
    
    this.getQuickReplyTags()
  },
  methods: {
    async getQuickReplyTags() {
      try {
        let id =this.$route.query.id;
        // 从后端获取快速回复标签
        lookAtTheCorrespondingDiseaseByLocation(id).then(res => {
          console.log("返回的数据: ",res)
          this.quickReplyTags = res
        })
      } catch (error) {
        console.error('获取快速回复标签失败：', error)
      }
    },
    // 滚动到底部
    async scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.chatContainer
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    },

    // 选择快速回复
    async selectQuickReply(tag) {
      this.inputMessage = tag;
      await this.sendMessage();
    },

    // 发送消息
    async sendMessage() {
      if (this.isLoading) return;
      if (!this.inputMessage.trim()) {
        this.$message.error('请输入内容')
        return
      }

      this.isLoading = true;
      // 添加用户消息
      this.chatMessages.push({
        type: 'user',
        content: this.inputMessage
      })
      
      // 保存聊天记录
      localStorage.setItem('chatMessages', JSON.stringify(this.chatMessages));

      const message = this.inputMessage
      this.inputMessage = ''
      await this.scrollToBottom()

      try {
        // 创建新的AI消息
        const aiMessage = {
          type: 'ai',
          content: '',
          doctorList: [] // 初始化医生列表为空数组
        }
        this.chatMessages.push(aiMessage)

        const eventSource = new EventSource(`/dev-api/call/ai/generateStreamAsString?message=${encodeURIComponent(message)}`)

        eventSource.onmessage = async (event) => {
          if (event.data === '[complete]') {
            this.isLoading = false;
            
            // 如果消息中包含医生推荐，获取并保存医生列表
            if (aiMessage.content.includes('提供的症状')) {
              try {
                const response = await weCanTraceTheSymptomsToTheDoctor(message);
                if (response && response.length > 0) {
                  aiMessage.doctorList = response; // 直接保存到消息对象中
                }
              } catch (error) {
                console.error('获取医生列表失败：', error);
              }
            }
            
            // 保存完整的聊天记录（包含医生列表）
            localStorage.setItem('chatMessages', JSON.stringify(this.chatMessages));
            
            // 检查完整的挂号成功消息
            if (aiMessage.content.includes('挂号成功！')||
                aiMessage.content.includes('成功挂上')) {
              console.log('检测到挂号成功消息，准备执行支付');


              const doctorMatch = aiMessage.content.match(/(\S{3})医生/);
              const priceMatch = aiMessage.content.match(/(\d+)元/);


                const doctorName = doctorMatch[1];
                const price = priceMatch[1];
                const orderNumber = Math.floor(Math.random() * 900000) + 100000;

              console.log('医生名称:', doctorName)

                // 使用原有的支付方法
                this.$confirm('是否确认支付?', '提示', {
                  confirmButtonText: '刷给我狠狠的刷',
                  cancelButtonText: '认清自己',
                  type: 'warning'
                }).then(() => {
                  window.open("http://127.0.0.1:9215/alipay/pay?subject="+doctorName+"&traceNo="+orderNumber+"&totalAmount="+price,'_blank')
                }).catch(() => {
                  this.$message({
                    type: 'info',
                    message: '已取消支付'
                  });
                });
            }

            eventSource.close();
            return;
          }
          
          aiMessage.content += event.data;
          this.scrollToBottom();
        }

        eventSource.onerror = (error) => {
          console.error('SSE错误:', error)
          this.isLoading = false;
          eventSource.close()
          if (!aiMessage.content) {
            aiMessage.content = '发送失败，请重试'
          }
          this.scrollToBottom()
        }

      } catch (error) {
        this.isLoading = false;
        console.error('发送消息失败:', error)
        const aiMessage = this.chatMessages[this.chatMessages.length - 1]
        if (aiMessage && aiMessage.type === 'ai') {
          aiMessage.content = '发送失败，请重试'
        }
        this.scrollToBottom()
      }
    },

    // 返回上一页
    goBack() {
      console.log('返回按钮')
      this.$router.back()
    },

    // 其他功能
    showHistory() {
      this.$message.info('查看历史记录')
    },

    startVoiceInput() {
      this.$message.info('开始语音输入')
    },

    uploadImage() {
      this.$message.info('上传图片')
    },

    async getDoctorList(tag) {
      try {
        const response = await weCanTraceTheSymptomsToTheDoctor(tag)
        // 更新医生列表
        this.doctorList = response
        await this.scrollToBottom()
      } catch (error) {
        console.error('获取医生列表失败：', error)
        this.$message.error('获取医生列表失败')
      }
    },

    // 处理挂号
    startConsult(doctor) {
      this.inputMessage = `我要挂${doctor.doctorName}医生的号`
      this.sendMessage()
    }
  },



  // 组件销毁时关闭 EventSource 连接
  beforeDestroy() {
    if (this.eventSource) {
      this.eventSource.close()
      this.eventSource = null
    }
  }
}
</script>

<style scoped lang="scss">
.ai-chat {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;

  .header {
    height: 44px;
    background-color: #4a90e2;
    color: white;
    display: flex;
    align-items: center;
    padding: 0 16px;
    position: relative;

    .back {
      font-size: 20px;
      padding: 8px;
      margin-left: -8px;
    }

    .title {
      flex: 1;
      text-align: center;
      font-size: 18px;
    }

    .notification {
      padding: 8px;
      margin-right: -8px;
    }
  }

  .chat-container {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    background-color: #f5f5f5;

    .message {
      margin-bottom: 16px;
      display: flex;
      align-items: flex-start;
      gap: 10px;

      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        overflow: hidden;
        flex-shrink: 0;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .message-content {
        max-width: 70%;
        padding: 12px 16px;
        border-radius: 16px;
        font-size: 14px;
        line-height: 1.5;
      }
    }

    .ai-message {
      .message-content {
        background-color: white;
        border-top-left-radius: 4px;
      }
    }

    .user-message {
      justify-content: flex-end;

      .message-content {
        background-color: #4a90e2;
        color: white;
        border-top-right-radius: 4px;
      }
    }
  }

  .quick-replies {
    margin: 20px 0;

    .quick-reply-hint {
      color: #666;
      font-size: 14px;
      margin-bottom: 12px;
    }

    .tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .tag-item {
        background-color: white;
        padding: 8px 16px;
        border-radius: 20px;
        font-size: 14px;
        color: #4a90e2;
        border: 1px solid #4a90e2;
        cursor: pointer;

        &:active {
          opacity: 0.8;
        }
      }
    }
  }

  .input-area {
    background-color: white;
    padding: 12px 16px;
    border-top: 1px solid #eee;

    .quick-replies {
      margin-bottom: 12px;

      .quick-reply-hint {
        color: #666;
        font-size: 14px;
        margin-bottom: 8px;
      }

      .tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;

        .tag-item {
          background-color: white;
          padding: 8px 16px;
          border-radius: 20px;
          font-size: 14px;
          color: #4a90e2;
          border: 1px solid #4a90e2;
          cursor: pointer;

          &:active {
            opacity: 0.8;
          }
        }
      }
    }

    .input-box {
      display: flex;
      align-items: center;
      background-color: #f5f5f5;
      border-radius: 4px;
      padding: 8px 12px;

      input {
        flex: 1;
        border: none;
        background: none;
        font-size: 14px;
        padding: 0;
        margin: 0;
        outline: none;

        &::placeholder {
          color: #999;
        }

        &:disabled {
          background-color: #f5f5f5;
          cursor: not-allowed;
        }
      }

      .send-btn {
        color: #4a90e2;
        font-size: 14px;
        padding: 4px 8px;
        cursor: pointer;

        &.disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        &:active {
          opacity: 0.8;
        }
      }
    }

    .action-buttons {
      display: flex;
      justify-content: space-around;

      .action-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        font-size: 12px;
        color: #666;
        cursor: pointer;



        &:active {
          opacity: 0.8;
        }
      }
    }
  }

  .doctor-list {
    margin-top: 12px;
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 12px;

    .doctor-list-title {
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
    }

    .doctor-cards {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    .doctor-card {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: white;
      padding: 12px;
      border-radius: 6px;
      border: 1px solid #eee;

      .doctor-info {
        flex: 1;

        .doctor-name {
          font-size: 14px;
          font-weight: bold;
          color: #333;
          margin-bottom: 4px;
        }

        .doctor-title {
          font-size: 12px;
          color: #666;
          margin-bottom: 2px;
        }

        .doctor-specialty {
          font-size: 12px;
          color: #4a90e2;
        }

        .doctor-price {
          font-size: 12px;
          color: #f56c6c;
          margin-top: 2px;
        }
      }

      .doctor-action {
        .consult-btn {
          padding: 6px 12px;
          background-color: #4a90e2;
          color: white;
          border: none;
          border-radius: 15px;
          font-size: 12px;
          cursor: pointer;

          &:hover {
            background-color: #357abd;
          }
        }
      }
    }
  }
}
</style>
